/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string") {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time);
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), "/");
      }
    }

    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    return value.toString().padStart(2, "0");
  });
  return time_str;
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (("" + time).length === 10) {
    time = parseInt(time) * 1000;
  } else {
    time = +time;
  }
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return "刚刚";
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + "分钟前";
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + "小时前";
  } else if (diff < 3600 * 24 * 2) {
    return "1天前";
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return (
      d.getMonth() +
      1 +
      "月" +
      d.getDate() +
      "日" +
      d.getHours() +
      "时" +
      d.getMinutes() +
      "分"
    );
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split("?")[1]).replace(/\+/g, " ");
  if (!search) {
    return {};
  }
  const obj = {};
  const searchArr = search.split("&");
  searchArr.forEach((v) => {
    const index = v.indexOf("=");
    if (index !== -1) {
      const name = v.substring(0, index);
      const val = v.substring(index + 1, v.length);
      obj[name] = val;
    }
  });
  return obj;
}

// 分钟数转化为天时分
export function getDuration(my_time) {
  var days = my_time / 60 / 24;
  var daysRound = Math.floor(days);
  var hours = my_time / 60 - 24 * daysRound;
  var hoursRound = Math.floor(hours);
  var minutes = my_time - 24 * 60 * daysRound - 60 * hoursRound;
  var minutesRound = Math.floor(minutes);

  return daysRound + "天" + hoursRound + "时" + minutesRound + "分";
}

/**
 * 防抖
 * @param {执行的函数} fn
 * @param {延迟执行的时间} delay
 * @param {是否立即执行} immediate
 */
export const debounce = (fn, delay, immediate = false) => {
  let timer = null;
  let isInvoke = false;

  const _debounce = function (...args) {
    return new Promise((resolve) => {
      if (timer) clearTimeout(timer);

      if (immediate && !isInvoke) {
        const result = fn.apply(this, args);
        resolve(result);
        isInvoke = true;
      } else {
        timer = setTimeout(() => {
          const result = fn.apply(this, args);
          resolve(result);
          isInvoke = false;
          timer = null;
        }, delay);
      }
    });
  };

  _debounce.cancel = function () {
    if (timer) clearTimeout(timer);
    timer = null;
    isInvoke = false;
  };

  return _debounce;
};

/**
 * 限制打印份数只能输入正整数
 * @param {输入的数值} value
 * @param {修改的对象} obj
 * @param {对象属性} key
 * @param {是否能输入小数点} dot
 */
export const limitInput = (value, obj, key, dot) => {
  if (!/^[0-9]\d*$/.test(value)) {
    const pattern = dot
      ? /[`~!@#$^\-+&*()=|{}':;',\\\[\]<>\/?~！@#￥……&*（）——|{}【】'；：""'。，、？\s\u4E00-\u9FA5]/g
      : /[`~!@#$^\-+&*()=|{}':;',\\\\.[\]<>\/?~！@#￥……&*（）——|{}【】'；：""'。，、？\s\u4E00-\u9FA5]/g;
    obj[key] = value.replace(pattern, "");
  }
};

/**
 * 获取前天、昨天、今天、明天、后天、大后天的日期
 * -2：前天，-1：昨天，0：今天，1：明天，2后天，3：大后天
 * @param {具体哪天} AddDayCount
 * @returns
 */
export function getDateStr(AddDayCount) {
  const dd = new Date();
  dd.setDate(dd.getDate() + AddDayCount); // 获取AddDayCount天后的日期
  const y = dd.getFullYear();
  const m = dd.getMonth() + 1; // 获取当前月份的日期
  const d = dd.getDate();
  return `${y}-${m < 10 ? "0" + m : m}-${d < 10 ? "0" + d : d}`;
}

export const downLoadXls = (res) => {
  const fileNames = res.headers["content-disposition"];
  if (fileNames) {
    //解码
    const fileName = decodeURIComponent(fileNames.match(/=(.*)$/)[1]);
    // 处理返回的文件流
    const content = res.data;
    const blob = new Blob([content], {
      type: "application/octet-stream; charset=utf-8",
    });
    if ("download" in document.createElement("a")) {
      //非IE下载
      const a = document.createElement("a"); //创建一个a标签
      a.download = fileName; //指定文件名称
      a.style.display = "none"; //页面隐藏
      a.href = URL.createObjectURL(blob); // href用于下载地址
      document.body.appendChild(a); //插到页面上
      a.click(); //通过点击触发
      URL.revokeObjectURL(a.href); //释放URL 对象
      document.body.removeChild(a); //删掉a标签
    } else {
      //IE10 + 下载
      navigator.msSaveBlob(blob, fileName);
    }
  }
};
export const strByLastSymbolSlice = (str, sign, index = 0) => {
  const getProxyIndex = str.lastIndexOf(sign) + index;
  const prefixStr = str.slice(0, getProxyIndex);
  const suffix = str.slice(getProxyIndex, str.length);
  return {
    prefixStr,
    suffix,
    index: getProxyIndex,
  };
};

export const arrConverObj = (arr = [], key) => {
  const obj = {};
  if (arr.length === 0 || !key) return obj;
  arr.map((item) => {
    obj[item[key] + ""] = item;
  });
  return obj;
};
